package org.example.dev.service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author 梁祖杰
 */
//实现邮箱发邮件功能，更换邮箱后邮箱名、授权码、smtp地址、smtp端口会变，注意修改
public class EmailService {
    public static void sendEmail(String to, String title, String body) {//收件人、标题、内容
        final String username = "GWSJ_SD@163.com";//邮箱名
        final String password = "YGrThRgsbDhUtyrV";//开启smtp服务后的授权码

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.163.com");//smtp地址
        props.put("mail.smtp.port", "25");//smtp端口

        Session session = Session.getInstance(props,
                new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(title);
            message.setText(body);

            Transport.send(message);

            System.out.println("Sent message successfully...");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}
